//
//  LPTprescriptionEditViewController.m
//  LPTClient
//
//  Created by mac on 2018/12/7.
//  Copyright © 2018年 zhaodd. All rights reserved.
//

#import "LPTprescriptionEditViewController.h"
#import "LPTComprositionEditFooterView.h"
#import "LPTComPositionEditCompTableViewCell.h"
#import "LPTCompositionEditTableViewCell.h"
#import "LPTCategoryModel.h"
#import "LPTComCategoryView.h"

@interface LPTprescriptionEditViewController ()<LPTComprositionEditFooterViewDelegate,LPTComCategoryViewDelegate,UINavigationBarDelegate,UINavigationControllerDelegate>

@property (nonatomic ,strong)NSMutableArray *preCombArray;
@property (nonatomic ,copy)NSArray *categorysArray;//所有中药列表
@property (nonatomic , assign) BOOL showCateList;//当前是否展示药方列表
@property (nonatomic ,strong)LPTComCategoryView *categoryView;//药方分类列表
@property (nonatomic ,strong)NSMutableArray *selectMedicineArray;//当前使用的药方列表
@property (nonatomic ,weak)UIView *backgroundView;//弹框背景

@end

@implementation LPTprescriptionEditViewController

-(LPTComCategoryView *)categoryView
{
    if (!_categoryView) {
        
        LPTComCategoryView *categoryView = [[LPTComCategoryView alloc] initWithComArray:self.categorysArray];
        categoryView.delegate = self;
        categoryView.hidden = YES;
        [self.view addSubview:categoryView];
        _categoryView = categoryView;
    }
    
    return _categoryView;
}

-(BOOL)navigationShouldPopOnBackButton
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您正在编辑处方，确定要返回吗？" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }]];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
    return NO;
}

-(UIView *)backgroundView
{
    if (_backgroundView == nil) {
        UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
        view.backgroundColor = [UIColor colorWithWhite:.3 alpha:.7];
        [self.view addSubview:view];
        _backgroundView = view;
    }
    
    return _backgroundView;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationController.delegate = self;
    self.preCombArray = [[NSMutableArray alloc] init];
    self.selectMedicineArray = [[NSMutableArray alloc] init];
    
    [self initSubViews];
    
    [self requestprescriptionList];
}

-(void)initSubViews
{
    LPTComprositionEditFooterView *footerView = [[LPTComprositionEditFooterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    footerView.delegate = self;
    self.tableView.tableFooterView = footerView;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 88;
    [self.dataSource addObjectsFromArray:@[@[@"组成"],@[@"名称"],@[@"功用"],@[@"主治"]]];
    
    if (self.type == kEditPreType && self.dic) {
        [self.preCombArray addObjectsFromArray:self.dic[@"recipe_items"]];
    }
    
    [self.tableView reloadData];
}

//设置当前每份中药数量
-(void)setcurrentMedicineCount
{
    for (LPTCategoryModel *model in self.categorysArray) {
        
        for (LPTMedicineModel *medicine in model.chinese_medicines) {
            
            for (NSDictionary *dic in self.preCombArray) {
                
                if ([medicine.medicineId isEqualToString:[NSString stringWithFormat:@"%@",dic[@"chinese_medicine"][@"id"]]]) {
                    medicine.count = [dic[@"weight"] integerValue];
                    [self.selectMedicineArray addObject:medicine];
                }
            }
        }
    }
}

//获取中药列表
-(void)requestprescriptionList
{
    [MMProgressHUD show];
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:@"/api/chinese_medicine_categories" withBody:@{}];
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
       
        [MMProgressHUD dismiss];
        self.categorysArray = [NSArray modelArrayWithClass:[LPTCategoryModel class] json:data[@"chinese_medicine_categories"]];
        [self setcurrentMedicineCount];
        [self.tableView reloadData];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        [MMProgressHUD dismiss];
    }];
}

//保存药方
-(void)saveprescription
{
    NSMutableDictionary *params = [NSMutableDictionary new];
    
    if ([self.dic valueForKey:@"id"]) {
        
        [params setValue:self.dic[@"id"] forKey:@"id"];
    }
    
    //名字
    LPTComPositionEditCompTableViewCell *nameCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    [params setValue:[nameCell getTextContent] forKey:@"name"];
    
    //功效
    LPTComPositionEditCompTableViewCell *effectCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    [params setValue:[effectCell getTextContent] forKey:@"effect"];
    
    //功效
    LPTComPositionEditCompTableViewCell *treatmentCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:3]];
    [params setValue:[treatmentCell getTextContent] forKey:@"treatment"];
    
    //成分
    NSArray *recipeArray = [self getRequestArray];
    
    if (!recipeArray.count) {
        [MMProgressHUD show];
        [MMProgressHUD dismissWithError:@"请添加中药成分"];
        return;
    }
    
    [params setValue:recipeArray forKey:@"recipe_items"];
    
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:@"/api/save_recipe" withBody:params withMethod:YTKRequestMethodPOST];
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
       
        [self.navigationController popViewControllerAnimated:YES];
        [MMProgressHUD show];
        [MMProgressHUD dismissWithSuccess:@"保存成功"];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        [MMProgressHUD show];
        [MMProgressHUD dismissWithError:data];
    }];
}

-(NSArray *)getRequestArray
{
    NSMutableArray *array = [NSMutableArray new];
    for (LPTMedicineModel *model in self.selectMedicineArray) {
        
        NSString *string = [NSString stringWithFormat:@"%@",model.medicineId];
        NSDictionary *dic = [NSDictionary dictionaryWithObject:@(model.count) forKey:string];
        [array addObject:dic];
    }
    
    return [array copy];
}

- (IBAction)rightItemAction:(id)sender {
    
    self.backgroundView.hidden = NO;
    self.categoryView.hidden = NO;
    
    [UIView animateWithDuration:.5 animations:^{
        
        self.categoryView.top = 0;
        
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - UITableViewDataSource & Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *sectionArray = self.dataSource[section];
    
    if (section == 0) {
        
        return self.selectMedicineArray.count;
    }else{
        
        return sectionArray.count;
    }
    
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0 && !self.selectMedicineArray.count) {
        
        //新增的第一个section
        return @"";
        
    }else{
        
        NSArray *sectionArray = self.dataSource[section];
        return [sectionArray firstObject];
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (!self.selectMedicineArray.count && section == 0) {
        
        return 0.1f;
    }else{
        return 40;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section != 0) {
        
        LPTComPositionEditCompTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTComPositionEditCompTableViewCell" forIndexPath:indexPath];
        if (indexPath.section == 1) {
            
            if (self.type == kEditPreType) {
                [cell refreshWithContent:self.dic[@"name"]];
            }
        }else if (indexPath.section == 2){
            
            if (self.type == kEditPreType) {
                
                [cell refreshWithContent:self.dic[@"effect"]];
            }
        }else if (indexPath.section == 3){
            
            if (self.type == kEditPreType) {
                
                [cell refreshWithContent:self.dic[@"treatment"]];
            }
        }
        return cell;
        
    }else{
        
        LPTCompositionEditTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LPTCompositionEditTableViewCell" forIndexPath:indexPath];
        LPTMedicineModel *dic = self.selectMedicineArray[indexPath.row];
        [cell refreshWihEntity:dic];
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self.tableView endEditing:YES];
}

#pragma mark - LPTComCategoryViewDelegate
-(void)comCategoryViewDidClickSureBtnWithArray:(NSArray *)array
{
    self.backgroundView.hidden = YES;
    [self.selectMedicineArray removeAllObjects];
    [self.selectMedicineArray addObjectsFromArray:array];
    self.categoryView.hidden = YES;
    [UIView animateWithDuration:.5 animations:^{
       
        self.categoryView.top = - 300;
    } completion:^(BOOL finished) {
        
    }];
    
    [self.tableView reloadData];
}

#pragma mark - LPTComprositionEditFooterViewDelegate
-(void)comprositionEditFooterViewDidClickSave
{
    [self saveprescription];
}

@end
